<template>
  <div class="mt20 wrap" v-loading="loading">
    <div v-for="item in formSection" :key="item.code">
      <anchor
        :title="item.title"
        v-if="
          item?.sectionLabel !== 'ADDRESS' &&
            item?.formTemplateFieldVOList &&
            item?.formTemplateFieldVOList.length &&
            (item.typeCode == 'LIST' ? true : detailsInfo[item.code])
        "
      >
        <el-button
          v-if="
            props.componentObject.templateCode === 'Procurement_Strategy_TD' &&
              item.code === 'sourcing_item_supplier_list' &&
              detailsInfo?.sourcing_item_basic?.searchRelationId
          "
          @click="handleGetResult"
          >企业关系</el-button
        >
      </anchor>
      <div v-if="item.typeCode == 'FORM' && detailsInfo[item.code]">
        <zcb-address
          v-if="item?.sectionLabel === 'ADDRESS'"
          :isPreview="true"
          :isPurchaser="true"
          :schema="item.formTemplateFieldVOList"
          v-model="detailsInfo[item.code]"
        ></zcb-address>
        <zcb-form
          v-else
          :isPreview="true"
          :isPurchaser="true"
          :changeInfos="changeInfos"
          :modelValue="detailsInfo[item.code] || {}"
          :schema="item.formTemplateFieldVOList"
          :options="formOptions"
          :currencyInfo="detailsInfo?.currency && !isEmptyObject(detailsInfo?.currency) ? detailsInfo?.currency : getTenantInfo()"
        >
          <!-- 评标方案 -->
          <template #evaluationName>
            {{
              detailsInfo[item.code]?.evaluationTemplateName
                ? detailsInfo[item.code]?.evaluationTemplateName + '-' + detailsInfo[item.code]?.evaluationTemplateCode
                : '--'
            }}
          </template>
          <!-- 开评标规则 -->
          <template #tenderEvaluationRule>
            <el-button type="info" link @click="goView({ detailsInfo: detailsInfo[item.code], code: 'tenderEvaluationRule', item })">{{
              t('keys.view')
            }}</el-button>
          </template>
          <template #businessRelation>
            <el-button type="info" link @click="goView({ detailsInfo: detailsInfo[item.code], code: 'businessRelation', item })">{{
              t('keys.Check_the_documents') + '(' + (detailsInfo[item.code]?.businessRelation || 0) + ')'
            }}</el-button>
          </template>
          <template #materialCode>
            {{ materialCode }}
          </template>
          <template #writePayFlowStage>
            {{ detailsInfo[item.code]?.writePayFlowStageCn || '--' }}
          </template>
        </zcb-form>
      </div>

      <div v-else-if="item.typeCode == 'LIST' && item?.fieldGroupVoList && item?.fieldGroupVoList.length > 0">
        <!-- 行组件 -->
        <row-edit-table-group
          sourceType="tableForm"
          :isPurchaser="true"
          :column="item.formTemplateFieldVOList"
          :fieldSection="item"
          :tableData="detailsInfo[item.code]"
          :checkbox="false"
          :showIndex="false"
          :canFixed="false"
          :showActionBtn="false"
          :isPreview="true"
          :isChangeFalg="true"
          :currencyInfo="detailsInfo?.currency && !isEmptyObject(detailsInfo?.currency) ? detailsInfo?.currency : getTenantInfo()"
          :changeInfos="changeInfos"
          ref="baseTableRef"
        >
          <!-- 引用价格-税率 -->
          <template #quotedTaxRate="{scope,column}">
            <span>{{
              scope[column.fieldCode]?.taxRateNum === undefined || scope[column.fieldCode]?.taxRateNum === null
                ? '--'
                : scope[column.fieldCode]?.taxRateNum === 0
                ? '0%'
                : scope[column.fieldCode]?.taxRateNum + '%'
            }}</span>
          </template>
        </row-edit-table-group>
      </div>
      <div v-else-if="item.typeCode == 'LIST'">
        <row-table-v1
          v-if="showpage"
          :isPurchaser="true"
          :isPreview="true"
          :showIndex="false"
          :column="item.formTemplateFieldVOList"
          :tableData="detailsInfo[item.code] || []"
          :showActionBtn="false"
          :currencyInfo="detailsInfo?.currency && !isEmptyObject(detailsInfo?.currency) ? detailsInfo?.currency : getTenantInfo()"
          :changeInfos="changeInfos"
        >
          <template #materialCode="{ scope }">
            {{ scope.materialCode || '--' }}
          </template>
          <template #material="{ scope }">
            {{ scope.materialCode || '--' }}
          </template>
        </row-table-v1>
      </div>
    </div>
  </div>
  <!-- 关闭弹窗 -->
  <el-dialog v-model="isShow" title="企业关系查询结果" isFull width="1000px">
    <div class="dialog-relation-box">
      <p class="title">关系图</p>
      <p><span class="red">橙色：查询企业</span><span class="bule">蓝色：中间关系体</span></p>
      <p>{{ apiStatusCn }}</p>
      <div style="height: calc(65vh)" v-if="apiStatus == 200">
        <zcbRelationGraph v-if="isShow" ref="graphRef" :options="graphOptions" />
      </div>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="isShow = false"> 确定 </el-button>
      </div>
    </template>
  </el-dialog>
  <strategyDialog ref="strategyDialogRef" />
</template>
<script setup>
import { ref, onMounted, nextTick } from 'vue'
import { getTenantInfo } from 'utils/headerToken'
import { isEmptyObject } from 'utils/validate'
import { getTempInIdfoApi, getTempInfoApi, rfxbusinessrelationshipsById } from '@/api/common'
import { ERR_OK } from 'config/statusCode'
import { formatTotalMoney } from 'utils/validate'
import listMixins from '@/hooks/useList'
import { useI18n } from 'vue-i18n'
import strategyDialog from './components/strategyDialog.vue'
const { t } = useI18n() // 中英文
const props = defineProps({
  componentObject: {
    // 返回的对象值
    type: Object,
    default() {
      return {}
    }
  }
})
console.log(props)
const loading = ref(false)
const formSection = ref([])
const detailsInfo = ref(JSON.parse(props.componentObject.detail))
const changeInfos = ref([])
const showpage = ref(false)
console.log(detailsInfo.value)
let { formOptions } = listMixins()
const strategyDialogRef = ref(null)
const goView = (params) => {
  console.log(params, strategyDialogRef.value)
  strategyDialogRef.value.show({ ...params })
}
//获取模版
const getTeml = async (templateId) => {
  loading.value = true
  showpage.value = false
  const { code, data } = await getTempInfoApi(templateId)
  if (code == ERR_OK) {
    let list = JSON.parse(JSON.stringify(data.formSectionVOList))
    formSection.value = list.filter(
      (item) => item.formTemplateFieldVOList && item.formTemplateFieldVOList.length > 0 && item.formTemplateFieldVOList != null
    )
    formSection.value.map((item) => {
      item.formTemplateFieldVOList = item.formTemplateFieldVOList.filter((item1) => {
        // return item1.displayPage.includes('PREVIEW_PAGE')
        return String(item1.displayPage).indexOf('PREVIEW_PAGE') > -1
      })
    })
    detailsInfo.value.currency = {}
    formSection.value.forEach((item) => {
      if (item.typeCode == 'FORM' && detailsInfo.value[item.code]?.currency && !isEmptyObject(detailsInfo.value[item.code]?.currency)) {
        detailsInfo.value.currency = detailsInfo.value[item.code]?.currency
        // detailsInfo.value.currency.currencySymbol = '$'
      }
      if (detailsInfo.value[item.code]?.changeInfos && Object.keys(detailsInfo.value[item.code]?.changeInfos).length) {
        changeInfos.value = detailsInfo.value[item.code]?.changeInfos
        console.log(changeInfos.value, 'changeInfos')
      }
      // 要货计划
      if (props.componentObject.templateCode === 'request_delivery_schedule' && item.code === 'ZDELIVER_PLAN.DELIVER_PLAN_LINE') {
        const isStandardconItem = item.formTemplateFieldVOList.find((h) => h.fieldCode == 'originPlanDeliverAmount')
        if (isStandardconItem) {
          isStandardconItem.isStandardIcon = JSON.parse(localStorage.getItem('tenantInfo')).currencySymbol
        }
      }
    })

    if (props.componentObject.templateCode === 'price_requisition_document' && detailsInfo.value?.price_requisition_basic?.orgScope === 'ALL') {
      // 定价申请  适用组织范围 = '全部时 不展示适用组织 行表格'
      formSection.value = formSection.value.filter((item) => item.code != 'organizational_information')
    }
    loading.value = false
    showpage.value = true
    console.log(formSection.value, 'formSection')
    console.log(detailsInfo.value, 'detailsInfo')
  }
}

// 企业关系弹窗相关内容
const graphRef = ref(null)
const isShow = ref(false)
const apiStatusCn = ref('')
const apiStatus = ref()
const graphOptions = ref({
  defaultJunctionPoint: 'border',
  disableNodeClickEffect: true
})
// 企业关系图
const handleGetResult = async () => {
  if (!detailsInfo.value?.sourcing_item_basic?.searchRelationId) return
  const { code, data } = await rfxbusinessrelationshipsById(detailsInfo.value?.sourcing_item_basic?.searchRelationId)
  const jsonData = {
    rootId: 'a',
    nodes: [],
    links: []
  }
  isShow.value = true
  apiStatusCn.value = data.apiStatusCn
  apiStatus.value = data.apiStatus
  nextTick(() => {
    if (data.businessRelationshipsContent?.nodes) {
      let { nodes, links } = data.businessRelationshipsContent
      nodes.forEach((t) => {
        if (t.label != 'P') {
          t.width = 300
          t.height = 50
          t.nodeShape = 1
        }
        if (containsSubstringIgnoreCaseAndBrackets(data.vendorName, t.text)) {
          t.color = '#ff8c00'
        }
      })
      jsonData.nodes = nodes
      jsonData.links = links
      graphRef.value.init(jsonData)
    }
  })
}
const containsSubstringIgnoreCaseAndBrackets = (mainStr, subStr) => {
  // 构建一个正则表达式，忽略中英文括号，并忽略大小写
  const regexPattern = subStr.replace(/[（）()]/g, '').replace(/[a-zA-Z]/g, (char) => `[${char.toLowerCase()}${char.toUpperCase()}]`)
  const regex = new RegExp(regexPattern, 'g')

  // 使用正则表达式测试主字符串是否包含子字符串
  return regex.test(mainStr.replace(/[（）()]/g, ''))
}
onMounted(() => {
  let { templateId, templateCode } = props.componentObject
  if (templateCode) {
    getTeml(templateCode)
  }
})
</script>

<style lang="scss" scoped>
.wrap {
  width: 98%;
  padding-right: 2%;
}
.mt20 {
  margin-top: 20px;
}
.title {
  display: flex;
  flex: 1;
  justify-content: space-between;
  & > div {
    color: var(--el-color-primary);
  }
}
.block {
  margin-bottom: 32px;
}
:deep(.row-table-v4) {
  padding-bottom: 32px;
}
:deep(.row-table) {
  padding-bottom: 0;
  .btn-list {
    padding: 0;
  }
}
.dialog-relation-box {
  .title {
    font-size: 20px;
    color: var(--el-color-primary);
  }
  p {
    margin-top: 5px;
    .red {
      color: rgb(255, 140, 0);
    }
    .bule {
      margin-left: 10px;
      color: blue;
    }
  }
}
</style>
